//
//  CXHNativeExpressViewController.m
//  CXHAdSDK_Example
//
//  Created by 陈坤 on 2022/4/9.
//  Copyright © 2022 陈桑葚吃桑葚. All rights reserved.
//

#import "CXHNativeExpressViewController.h"
#import <CXHAdSDK-Core/CXHAdSDKNativeExpressAd.h>
#import <MJRefresh/MJRefresh.h>
#import <CXHAdSDK-Adapter/CXHAdSDKAdapter.h>
#import <CXHAdSDK-Core/CXHBWTAdContainerView.h>

@interface CXHNativeViewCell : UITableViewCell

@property (nonatomic, strong, nullable) UIView *adView;

@end

@implementation CXHNativeViewCell

- (void)setAdView:(UIView *)adView {
    [_adView removeFromSuperview];
    
    _adView = adView;
    [self.contentView addSubview:_adView];
}

@end

@interface CXHNativeExpressViewController ()<UITableViewDelegate, UITableViewDataSource, CXHAdSDKNativeExpressAdDelegate>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *items;

@property (nonatomic, strong) CXHAdSDKNativeExpressAd *nativeExpressAd;

@property (nonatomic, strong) CXHBWTAdContainerView *adContainerView;

@end

@implementation CXHNativeExpressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIBarButtonItem *itemLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(onCancelClicked:)];
    self.navigationItem.leftBarButtonItem = itemLeft;
    
    UIButton *btn2 = [UIButton new];
    btn2.backgroundColor = [UIColor orangeColor];
    btn2.layer.cornerRadius = 20;
    
    UIBarButtonItem *itemRight = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(onRefreshClicked:)];
    self.navigationItem.rightBarButtonItem = itemRight;
    
    _items = [NSMutableArray new];
    
    _tableView = [UITableView new];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [_tableView registerClass:[CXHNativeViewCell class] forCellReuseIdentifier:@"adcell"];
    [self.view addSubview:_tableView];
    _tableView.frame = self.view.bounds;
}

- (void)onCancelClicked:(id)sender {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

// load ad
- (void)onRefreshClicked:(id)sender{
    if (!_nativeExpressAd) {
        CXHAdSDKNativeExpressAd *expressAd = [[CXHAdSDKNativeExpressAd alloc]initWithAdSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 10)];
        expressAd.delegate = self;
        expressAd.controller = self;
        expressAd.posId = @"35712573";
        _nativeExpressAd = expressAd;
    }
    [_nativeExpressAd load:2];
}

#pragma mark - UITableViewDelegate,UITableViewDateSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    id obj = [self.items objectAtIndex:indexPath.row];
    if ([obj conformsToProtocol:@protocol(CXHAdapterNativeExpressAdViewDelegate)]) {
        CXHNativeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"adcell" forIndexPath:indexPath];
        cell.adView = obj;
        return cell;
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.text = [NSString stringWithFormat:@"ListViewitem %li", indexPath.row];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    id item = [_items objectAtIndex:indexPath.row];
    if([item conformsToProtocol:@protocol(CXHAdapterNativeExpressAdViewDelegate)]) {
        return [(UIView *)item frame].size.height;
    } else {
        return 150;
    }
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if([cell isKindOfClass:[CXHNativeViewCell class]]) {
        [(CXHNativeViewCell *)cell setAdView:nil];
    }
}

#pragma mark - CXHAdSDKNativeExpressAdDelegate

/**
 信息流广告请求成功

 @param nativeAd 广告实例
 @param adViewArray 广告模板集合
 */
- (void)CXH_nativeAdSucessToLoad:(CXHAdSDKNativeExpressAd *)nativeAd
                     adViewArray:(NSArray<__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *> *)adViewArray{
//    [self.adItems addObjectsFromArray:adViewArray];
    for (UIView<CXHAdapterNativeExpressAdViewDelegate> *adView in adViewArray) {
        [adView render];
    }
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

/**
 信息流广告请求失败

 @param nativeAd 广告实例
 @param error 请求错误描述
 */
- (void)CXH_nativeAdFailToLoad:(CXHAdSDKNativeExpressAd *)nativeAd
                         error:(NSError *)error{
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

/**
 信息流广告渲染成功

 @param adView 广告视图
 */
- (void)CXH_nativeAdViewRenderOrRegistSuccess:(UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    // 6、注册或渲染成功，此时高度正常，可以展示
    dispatch_async(dispatch_get_main_queue(), ^{
        for (int i = 0; i < 6; i ++) {
            [self.items addObject:[NSNull null]];
        }
        [self.items addObject:adView];
        [self.tableView reloadData];
    });
}

/**
 信息流广告渲染失败

 @param adView 广告视图
 */
- (void)CXH_nativeAdViewRenderOrRegistFail:(UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    
}

/**
 信息流广告被点击

 @param nativeAd 广告模板
 */
- (void)CXH_nativeAdClicked:(CXHAdSDKNativeExpressAd *)nativeAd
                     adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView loadingPageURL:(NSString *)loadingPageURL{
    
}

/**
 信息流广告被关闭
 
 @param nativeAd 广告模板
 */
- (void)CXH_nativeAdClose:(CXHAdSDKNativeExpressAd *)nativeAd
                   adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.items removeObject:adView];
        [self.tableView reloadData];
    });
}

/**
 信息流广告被展示
 
 @param nativeAd 广告实例
 */
- (void)CXH_nativeAdExposure:(CXHAdSDKNativeExpressAd *)nativeAd
                      adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    
}

/**
 信息流广告落地页被关闭
 
 @param nativeAd 广告实例
 */
- (void)CXH_nativeAdCloseLandingPage:(CXHAdSDKNativeExpressAd *)nativeAd
                              adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    
}

@end
